// @charset "utf-8";
define(function (require, exports, module) {
	var Backbone = require('backbone');
	var clientData = require('../lib/clientdata');

	var ClientBaseModel = Backbone.Model.extend({
		filePath : '',
		file : '',
		getData : function () {
			var self = this;
			return clientData.getFileContent(('' === self.filePath ? self.file : self.filePath+'\\'+self.file));
		},
		saveData : function (data) {
			var self = this;
			var file = ('' === self.filePath ? self.file : self.filePath+'\\'+self.file);
			clientData.writeFileContent(file, data);
		},
		sortData : function (sortBy, sortWay, list, page) {
			var self = this;
			list = list.sort(self.sortTableFun(sortBy, sortWay));
			return self.getPageData(page, list);
		},
		sortTableFun : function (sortBy, srotWay) {
			var ordAlpah = (srotWay == 'asc') ? '>' : '<';
			// var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + ' ? 1 : -1');
			var sortFun = new Function('a', 'b', 'if(isNaN(parseFloat(a.' + sortBy + '))){return 1;}if(isNaN(parseFloat(b.' + sortBy + '))){return -1;} return parseFloat(a.' + sortBy + ')' + ordAlpah + 'parseFloat(b.' + sortBy + ') ? 1 : -1');
			return sortFun;
		},
		getPageData : function (page, pageSize, list) {
			var index = 1;
			var pageData = [];

			for (var i in list) {
				if (page === Math.ceil(index/pageSize)) {
					pageData.push(list[i]);
				}
				if (page < Math.ceil(index/pageSize)) {
					index++;
					break;
				}
				index++;
			}

			return {
				data : pageData,
				length : list.length
			};
		},
		searchData : function (keywords, searchBy, list) {
			var result = [];
			for (var i in list) {
				if ('all' === keywords || -1 !== (''+list[i][searchBy]).indexOf(keywords)) {
					result.push(list[i]);
				}
			}

			return result;
		}
	});

	module.exports = ClientBaseModel;
});